#pragma once
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <unistd.h>
#include <vector>
#define TaskNum 3
typedef void (*task_t)(); // task_t 函数指针类型

void Print()
{
    std::cout << "this is print task!!!" << std::endl;
}
void DownLoad()
{
    std::cout << "this is download task!!!" << std::endl;
}
void Flush()
{
    std::cout << "this is flush task!!!" << std::endl;
}
task_t tasks[TaskNum];
void LoadTask()
{
    srand(time(nullptr) ^ getpid() ^ 1777);//(数字随意，主要让它的随意性更强)
    tasks[0] = Print;
    tasks[1] = DownLoad;
    tasks[2] = Flush;
}

void ExcuteTask(int num)
{
    if (num < 0 || num > 2)
        return;
    tasks[num]();
}

int SelectTask()
{
    return rand()%TaskNum;//TaskNum就是任务数量；这里就是3；取模只会得到0~2的数。
}

void work()
{
    while (true)
    {
        int command = 0;
        int n = read(0, &command, sizeof(command));
        if (n == sizeof(command))
        {
            std::cout << "pid:" << getpid() << "handler task" << std::endl;
            ExcuteTask(command);
        }
        else if (n == 0)
        {
            std::cout << "process pid:" << getpid() << "quit" << std::endl;
            break;
        }
    }
}

void work1()
{
    while(true)
    {
        
        int command = 0;
        int n = read(0, &command, sizeof(command));
        if (n == sizeof(command))
        {
            std::cout << "pid is:" << getpid() << "handler task" << std::endl;
            ExcuteTask(command);
        }
        else if (n == 0)
        {

            usleep(500000);
            std::cout << "sub process pid:" << getpid() << "quit" << std::endl;
            
            break;
            
        }
    }
       

}

void work2()
{
    while (true)
    {
        int command = 0;
        int n = read(0, &command, sizeof(command));
        if (n == sizeof(command))
        {
            std::cout << "pid:" << getpid() << "handler task" << std::endl;
            ExcuteTask(command);
        }
        else if (n == 0)
        {
            std::cout << "process pid:" << getpid() << "quit" << std::endl;
            break;
        }
    }
}